/**
 * WanlShop状态管理器 - 用户管理
 * 
 * @ author 深圳前海万联科技有限公司 <wanlshop@i36k.com> 
 * < 程序仅用作FastAdmin付费插件API测试使用，未经版权所有权人书面许可，不能用于商业用途！>
 * @ link http://www.wanlshop.com
 * @ 2020年9月29日19:00:46
 * @ version 1.0.0
 **/
import http from '@/shopro/request/index'
import store from '@/shopro/store'
import tools from '@/shopro/utils/tools'
import wechat from '@/shopro/wechat/wechat'
import share from '@/shopro/share'



const state = {
	id: 0, //用户ID
	isLogin: false, // 登录状态
	username: '', // 用户名
	nickname: '', // 昵称
	mobile: '', // 手机号
	avatar: '', // 默认头像
	level: 0, // 等级
	gender: 0, // 性别
	birthday: '', // 生日
	bio: '', // 签名
	money: '0.00', // 余额
	score: 0, // 积分
	successions: '', // 连续登录天数
	maxsuccessions: '', // 最大连续登录天数
	prevtime: '', // 上次登录时间
	logintime: '', // 登录时间
	loginip: '', // 加入IP
	jointim: '', // 加入时间
	// token: '', // 令牌
	pushs: true, // 推送
	shock: true, // 震动
	voice: true, // 提示音
	
	token: uni.getStorageSync("token") || "",
	isLogin: uni.getStorageSync("isLogin") || false, // 是否登陆
	userInfo: uni.getStorageSync("userInfo") || {}, // 用户信息
	agentInfo: {}, //分销商信息
	userData: {}, //用户其他相关信息
	subscribeMessageIdsMap: [], //小程序订阅消息模板ids
	authType: '' // smsLogin:手机号登录注册, accountLogin:密码登录, forgotPwd:忘记密码, changePwd:修改密码, bindMobile:绑定手机号
}
const getters = {
	token: state => state.token,
	isLogin: state => state.isLogin,
	userInfo: state => state.userInfo,
	agentInfo: state => state.agentInfo,
	userOtherData: state => state.userData,
	authType: state => state.authType,
	subscribeMessageIdsMap: state => state.subscribeMessageIdsMap,
		
}
const mutations = {
	setUserInfo(state, payload) {
		for (let i in payload) {
			for (let j in state) {
				if (i === j) {
					state[j] = payload[i];
				}
			}
		}
		uni.setStorageSync("wanlshop:user", state);
		uni.setStorageSync("userInfo", state);
	},
	token(state, payload) {
		state.token = payload;
		uni.setStorageSync("token", payload);
	},
	// 登录态
	isLogin(state, data) {
		state.isLogin = data;
		uni.setStorageSync('isLogin', data);
	},
	// 用户信息
	userInfo(state, data) {
		state.userInfo = data;
		uni.setStorageSync("userInfo", data);
	},
	// 分销商信息
	AGENT_INFO(state, data) {
		state.agentInfo = data;
	},
	// 小程序订阅消息模板ids
	MESSAGE_IDS(state, data) {
		state.subscribeMessageIds = data;
	},
	USER_DATA(state, data) {
		state.userData = data;
	},
	AUTH_TYPE(state, data) {
		data ? uni.hideTabBar() : uni.showTabBar();
		state.authType = data;
	},

	// 订阅消息
	subscribeMessage(state, type) {
		let arr = state.subscribeMessageIdsMap[type];
		arr.length && uni.requestSubscribeMessage({
			tmplIds: arr,
			success: (res) => {
				console.log(res);
			},
			fail: (err) => {
				console.log(err);
			}

		});
	},

	// 解析订阅消息数据
	formatMessage(state, messageIdsObj) {
		// 各场景下用到的订阅模板
		let typeMap = {
			'result': ['order_sended'], //支付成功
			'grouponResult': ['groupon_success', 'groupon_fail', 'order_sended'], //拼团支付成功后
			'aftersale': ['refund_agree', 'aftersale_change', 'wallet_change'], //点击售后
			'wallet': ['score_change', 'wallet_apply', 'wallet_change'], //提现提醒
			'store': ['store_order_new'], //门店新订单通知
			'storeApply': ['store_apply'] //门店申请通知
		}
		let idsMap = {}
		Object.keys(typeMap).forEach(key => {
			idsMap[key] = []
			typeMap[key].forEach(item => {
				idsMap[key].push(messageIdsObj[item])
			})
		})
		state.subscribeMessageIdsMap = idsMap
	},
}

const actions = {
	async login({
		state,
		commit,
		dispatch,
		rootState
	}, data) {
		console.log(data)
		commit('setUserInfo', data.userinfo);
		uni.setStorageSync('userInfo',data.userInfo)
		state.isLogin = true; // 登录状态强制 开启
		// 根据notice.vue 而知，fastadmin没有此三项默认字段，手动添加，想同步修改该这两处即可
		state.pushs = true; // 推送
		state.voice = true; // 提示音
		state.shock = true; // 震动
		uni.setStorageSync("wanlshop:user", state);
		
		uni.setStorageSync("token", data.userinfo.token);
		// 统计信息
		dispatch('getUserInfo')
		dispatch('statistics', data.statistics)
	},

	async logout({
		state,
		rootState
	}) {
		for (let j in state) {
			state[j] = ''
		}
		state.isLogin = false;
		let statistics = rootState.statistics;
		for (let j in statistics) {
			for (let i in statistics[j]) {
				statistics[j][i] = 0
			}
		}
		// 从本地缓存中异步移除指定key
		uni.removeStorageSync('wanlshop:user');
		uni.removeStorageSync('wanlshop:statis');
		// 关闭即时通讯
		uni.closeSocket();
	},
	async statistics({
		state,
		dispatch,
		rootState
	}, payload) {
		let states = rootState.statistics;
		for (let i in payload) {
			for (let j in states) {
				if (i === j) {
					states[j] = payload[i];
				}
			}
		}
		uni.setStorageSync("wanlshop:statis", states);
	},
	getUserInfo({
		commit,
		dispatch,
		getters,
		state
	}, token = '') {
		return new Promise((resolve, reject) => {
			console.log(333)
			token && uni.setStorageSync('token', token);
			http('user.info').then(res => {
					console.log(res)
					if (res.code === 1) {
						let lastLoginStatus = getters.isLogin;
						commit('userInfo', res.data);
						commit('isLogin', true);
						dispatch('showAuthModal', '');
							uni.setStorageSync("userInfo", state);
						!lastLoginStatus && share.setShareInfo();
						// 存在分享信息 添加分享记录
						let spm = uni.getStorageSync('spm');
						if (spm) {
							http('common.shareAdd', {
								spm: spm
							});
							uni.removeStorageSync('spm');
						}
						resolve(res.data)
					}

				}).then(() => {
					// 只有在登录的时候请求购物车信息，订单信息，获取登录信息之后。
					token && dispatch('getCartList');
					token && dispatch('getUserData');
				})
				.catch(e => {
					reject(e)
				})
		})
	},
	// 用户其他相关信息
	getUserData({
		commit
	}) {
		return new Promise((resolve, reject) => {
			http('user.userData').then(res => {
				commit('USER_DATA', res.data);
				resolve(res)
			}).catch(e => {
				reject(e)
			})
		})
	},

	// 获取分销商身份信息
	getAgent({
		commit
	}) {
		return new Promise((resolve, reject) => {
			http('commission.auth').then(res => {
				if (res.code === 1) {
					console.log(res)
					commit('AGENT_INFO', res.data.data);
				}
				resolve(res)
			}).catch(e => {
				reject(e)
			});
		})
	},


	// 自动登录
	async autoLogin({
		getters,
		dispatch
	}) {
		if (getters.initWechat?.autologin && !getters.isLogin) { // 微信开启自动登录 并且当前未登录，进入自动登录流程
			let token = '';
			// #ifdef H5
			wechat.login();
			// #endif
			// #ifdef MP-WEIXIN
			token = await wechat.getWxMiniProgramSessionKey(true);
			// #endif
			token && await dispatch('getUserInfo', token);
		} else if (getters.isLogin) { // 已经登录，直接获取用户信息
			await dispatch('getUserInfo');
		}
		share.setShareInfo();
		// 初始化小程序session_key
		// #ifdef MP-WEIXIN
		if (!getters.initWechat?.autologin) {
			await wechat.getWxMiniProgramSessionKey(false);
		}
		// #endif
	},

	// 登录弹窗控制
	showAuthModal({
		commit
	}, type = 'accountLogin') {
		commit('AUTH_TYPE', type);
	},

	// // 退出登录
	// logout({
	// 	commit,
	// 	dispatch
	// }) {
	// 	uni.getStorageSync('token') && http('user.logout');
	// 	commit('token', "");
	// 	uni.removeStorageSync('chatSessionId');
	// 	commit('isLogin', false);
	// 	commit('userInfo', {});
	// 	commit('CART_LIST', []);
	// 	commit('USER_DATA', {});
	// 	// 重置全局分享信息
	// 	share.setShareInfo();
	// },

	// 获取订阅消息模板ids;
	getMessageIds({
		commit,
		state
	}) {
		http('user.messageIds').then(res => {
			commit('formatMessage', res.data)
			Promise.resolve(res.data)
		}).catch(e => {
			Promise.reject(e)
		})

	}


}



export default {
	// namespaced: true,
	state,
	mutations,
	actions,
	getters
}
